package cn.shanke.torrentmanagerserver.core;

import cn.shanke.torrentmanagerserver.controller.common.ResponseModel;
import cn.shanke.torrentmanagerserver.service.ConfigService;
import cn.shanke.torrentmanagerserver.util.ApplicationContextUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class AuthInterceptor implements  HandlerInterceptor {

    private ConfigService configService = ApplicationContextUtil.getBean(ConfigService.class);

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
//        System.out.println("执行了TestInterceptor的preHandle方法");
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//        System.out.println(request.getRequestURI());
//        System.out.println(basePath);
        response.setHeader("Access-control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        String token = request.getHeader(AuthTool.TOKEN_KEY);
        if (!AuthTool.checkToken(token, configService.getCurrent().getPasskey())) {
//            response.sendRedirect(URL_AUTH_FAIL);
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().write(ResponseModel.model(ResponseModel.CODE_NO_AUTH,"认证失败").toJsonString());
            response.getWriter().flush();
            return false;
        }
        return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//         System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }

}
